package tt.langchain4j.core;

import java.util.function.Supplier;


public class BufferSupplier<T> implements Supplier<T> {

    private T target = null;

    private volatile boolean buffered = false;

    private final Supplier<T> source;

    public BufferSupplier(Supplier<T> source) {
        this.source = source;
    }

    @Override
    public T get() {
        if ( buffered ) {
            return target;
        }
        synchronized ( this ) {
            if ( buffered ) {
                return target;
            }
            target = source.get();
            buffered = true;
        }
        return target;
    }

}
